#-*- coding:utf-8 -*-
from __future__ import unicode_literals

import cookielib
import datetime
import json
import re
import ssl
import time
import urllib
import urllib2

import damatuWeb
import db_pymsql

from sendmail import sendmail
from station_names import station_names

ssl._create_default_https_context=ssl._create_unverified_context
station_names=station_names.decode('utf-8')
city={};city2={}
seat={'二等座':'O','一等座':'M','硬卧':'3','软卧':'4','硬座':'1','无座':'1'}
for i in station_names.split('@'):
    if not i:
        continue
    tmp=i.split('|')
    city[tmp[1]]=tmp[2]
    city2[tmp[2]]=tmp[1]

class Train():
    def __init__(self,username='',password=''):
        self.orderlist={
        "train_date":"2017-10-27",
        "tk":"南宁东",
        "ar":"三水南",
        'choose_seats':"",
        "train_no":['K1558'],#["K1558"],
        "passenger_name":"",
        's1':'',
        's2':'',
        }
        self.username=username
        self.password=password
        self.c=cookielib.LWPCookieJar()
        self.cookie=urllib2.HTTPCookieProcessor(self.c)
        self.opener=urllib2.build_opener(self.cookie)
        urllib2.install_opener(self.opener)
        self.getQurl()
        self.tmp_list=[]
        self.s1=''
        self.s2=''
        self.n=0
        self.seatType=seat.get(self.orderlist.get('choose_seats'))
        self.tk=self.orderlist.get('tk')
        self.ar=self.orderlist.get('ar')
        self.from_station=city.get(self.tk)
        self.to_station=city.get(self.ar)
        self.train_date=self.orderlist.get('train_date')
        self.mydb=db_pymsql.db_mysql()

    def changeState(self,state,remark,state_ori=0):
        try:
            from models import Order
            order=Order.objects.filter(state=state_ori).first()
            order.remark=remark
            order.state=state
            order.save()
            return True
        except Exception as e:
            print '数据库写入报错:',e

    def getPage(self,url,data=None,timeout=15):
        try:
            headers={
            'User-Agent':'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.96 Safari/537.36',
            'Referer':'https://kyfw.12306.cn/otn/leftTicket/init',
            }
            req=urllib2.Request(url,data=data,headers=headers)
            h=self.opener.open(req,timeout=timeout)
            if h.getcode()==200:
                return h.read()
            elif h.getcode()==302:
                self.getPage(h.geturl())
            else:
                print h.getcode()
        except Exception as e:
            print url,'请求报错:',e

    def getQurl(self):
        h=self.getPage('https://kyfw.12306.cn/otn/leftTicket/init')
        if h:
            self.CLeftTicketUrl=re.findall("var CLeftTicketUrl = '(.*?)';",h)[0]

    def getCode(self):
        from io import BytesIO
        codeimg=self.getPage('https://kyfw.12306.cn/passport/captcha/captcha-image?login_site=E&module=login&rand=sjrand')
        self.out=BytesIO()
        self.out.write(codeimg)
        self.out.seek(0)
        #self.changeState(1,'生成获取验证码成功')

    def code(self):
        self.getCode()
        cod= damatuWeb.codeCal(self.out.read())
        print(cod)
        data={
            'answer':cod,
            'login_site':'E',
            'rand':'sjrand',
            }
        data=urllib.urlencode(data)
        h=self.getPage('https://kyfw.12306.cn/passport/captcha/captcha-check',data=data)
        h=json.loads(h)
        if h and h['result_code']=='4':
            print(h['result_message'])
            self.login()
            return True
        else:
            print(h['result_message'])
            self.code()

    def code2(self):
        self.getCode()
        cod= damatuWeb.codeCal(self.out.read())
        print(cod)
        data={
            'answer':cod,
            'login_site':'E',
            'rand':'sjrand',
            }
        data=urllib.urlencode(data)
        h=self.getPage('https://kyfw.12306.cn/passport/captcha/captcha-check',data=data)
        h=json.loads(h)
        if h and h['result_code']=='4':
            #self.changeState(2,'识别获取验证码成功',1)
            print(h['result_message'])
            login_user=self.login()
            return login_user
        else:
            print(h['result_message'])
            self.code2()

    def login(self):
        print 'cookie id:',id(self.c)
        data={
            'username':self.username,
            'password':self.password,
            'appid':'otn',
            }
        data=urllib.urlencode(data)
        req=urllib2.Request('https://kyfw.12306.cn/passport/web/login',data=data)
        h=self.opener.open(req).read()
        h=json.loads(h)
        if h['result_code']==0:
            print(h["result_message"])
            req=urllib2.Request('https://kyfw.12306.cn/passport/web/auth/uamtk',data='appid=otn')
            print('登陆成功后获取newapptk:')
            h=self.opener.open(req).read()
            print h
            if h:
                newapptk=json.loads(h).get('newapptk')
                print '发送请求newapptk'
                req=urllib2.Request('https://kyfw.12306.cn/otn/uamauthclient',data='tk=%s'%newapptk)
                h=self.opener.open(req).read()
                if h:
                    apptk=json.loads(h).get('apptk')
                    print h
                    #self.c.save(ignore_expires=True,ignore_discard=True)
                    #self.changeState(3,'登陆成功',2)
                    return json.loads(h).get('username')
        else:
            print(h["result_message"])
            return False

    def getTrain(self,CLeftTicketUrl,train_date,from_station,to_station):
        url='https://kyfw.12306.cn/otn/%s?leftTicketDTO.train_date=%s&leftTicketDTO.from_station=%s&leftTicketDTO.to_station=%s&purpose_codes=ADULT'%(CLeftTicketUrl,train_date,from_station,to_station)
        h=self.getPage(url).decode('utf-8')
        #print h
        if '网络可能存在问题' not in h:
            h=json.loads(h)
            if h['httpstatus']==200:
                return h['data']['result']
        else:
            print('网络可能存在问题,3秒后重试!')
            return False
    def getTrain2(self,train_date,from_station,to_station):
        url='https://kyfw.12306.cn/otn/%s?leftTicketDTO.train_date=%s&leftTicketDTO.from_station=%s&leftTicketDTO.to_station=%s&purpose_codes=ADULT'%(self.CLeftTicketUrl,train_date,from_station,to_station)
        h=self.getPage(url).decode('utf-8')
        if '网络可能存在问题' not in h:
            h=json.loads(h)
            if h['httpstatus']==200:
                data=[]
                for i in h['data']['result']:
                    t=i.split("|")
                    t[6]=city2.get(i.split("|")[6])
                    t[7]=city2.get(i.split("|")[7])
                    data.append(t)
                return data
        else:
            print('网络可能存在问题,3秒后重试!')
            return False

    def initDc(self):
        print '>>>初始化2个参数'
        h=self.getPage('https://kyfw.12306.cn/otn/confirmPassenger/initDc',data='_json_att=')
        rp=re.findall("var globalRepeatSubmitToken = '(.*?)'",h)[0]
        key_check_isChange = re.findall(r"key_check_isChange':'(.*?)'",h)[0]
        return rp,key_check_isChange


    def getPassenger(self,rp,key_check_isChange):
        data = {
                '_json_att':'',
                'REPEAT_SUBMIT_TOKEN':rp
            }
        data = urllib.urlencode(data)
        h=self.getPage('https://kyfw.12306.cn/otn/confirmPassenger/getPassengerDTOs',data=data)
        h=json.loads(h)
        print '>>>获取乘客信息以供选择:'
        n=0
        for k in h["data"]["normal_passengers"]:
            print n,k['passenger_name'],k['passenger_id_no'],k['mobile_no']
            n+=1
        print '>>>获取乘客信息'#下单环节3
        num=raw_input('请选择乘客(0~8),多个乘客请输入(0,1):')
        num=num.split(',')
        for i in num:
            self.s1+='%s,0,1,%s,1,%s,%s,N_'%(seatType,h["data"]["normal_passengers"][int(i)]["passenger_name"],h["data"]["normal_passengers"][int(i)]["passenger_id_no"],h["data"]["normal_passengers"][int(i)]["mobile_no"])
            self.s2+='%s,1,%s,1_'%(h["data"]["normal_passengers"][int(i)]["passenger_name"],h["data"]["normal_passengers"][int(i)]["passenger_id_no"])
        return self.s1,self.s2

    def dealInfo(self,a):
        a=a.replace("'",'"')
        b=a.split(',{')
        n=0
        list1=[]
        list2=[]
        s=''
        for i in a:
            if i!='}':
                s+=i
            else:
                s+=i
                list1.append(s)
                s=''
        for i in list1:
            i=i.replace(',{','{')
            i=i.replace("'",'"')
            k=json.loads(i)
            list2.append((n,k['passenger_name'],k['passenger_id_no'],k['mobile_no']))

            print n,k['passenger_name'],k['passenger_id_no'],k['mobile_no']
            if self.orderlist.get("passenger_name"):
                if ',' in self.orderlist.get("passenger_name"):
                    for j in self.orderlist.get("passenger_name").split(','):
                        if j==k['passenger_name']:
                            self.s1+='%s,0,1,%s,1,%s,%s,N_'%(seatType,k['passenger_name'],k['passenger_id_no'],k['mobile_no'])
                            self.s2+='%s,1,%s,1_'%(k['passenger_name'],k['passenger_id_no'])
                else:
                    if self.orderlist.get("passenger_name")==k['passenger_name']:
                            self.s1+='%s,0,1,%s,1,%s,%s,N_'%(self.seatType,k['passenger_name'],k['passenger_id_no'],k['mobile_no'])
                            self.s2+='%s,1,%s,1_'%(k['passenger_name'],k['passenger_id_no'])
            n+=1
        print self.s1,self.s2,list2
        return self.s1,self.s2,list2

    def getPassInfo(self):
        h=self.getPage('https://kyfw.12306.cn/otn/passengers/init').decode('utf-8')
        #if 'globalRepeatSubmitToken = null'not in h:self.c.save(ignore_expires=True,ignore_discard=True)
        if 'var passengers=[' in h:
            print '>>>从我的乘车人获取乘客信息!'
            p=h.split('var passengers=[')[1].split('];')[0]
            self.s1,self.s2,list2=self.dealInfo(p)
            #self.c.save(ignore_expires=True,ignore_discard=True)
            #self.changeState(4,'获取乘车人信息成功',3)
            return self.s1,self.s2,list2
        elif 'globalRepeatSubmitToken = null' in h:
            print '>>>重新登陆中!!!'
            self.code2()
            self.s1,self.s2,list2=self.getPassInfo()
            return self.s1,self.s2,list2


    def checkOrderInfo(self,s1,s2,rp):
        print '>>>检查订单信息'
        data = {
            'cancel_flag':'2',
            'bed_level_order_num':'000000000000000000000000000000',
            'passengerTicketStr':self.s1.encode('utf-8'),
            'oldPassengerStr':self.s2.encode('utf-8'),
            'tour_flag':'dc',
            'randCode':'',
            '_json_att':'',
            'REPEAT_SUBMIT_TOKEN':rp
        }
        data=urllib.urlencode(data)
        h=self.getPage('https://kyfw.12306.cn/otn/confirmPassenger/checkOrderInfo',data=data)
        print '确认订单信息:',h

    def getQueueCount(self,seatType,from_station,to_station,rp):
        print '>>>查询当前剩余的票数:'
        data={
            'train_date':'Thu Oct 14 2017 00:00:00 GMT+0800 (中国标准时间)'.encode('utf-8'),
            'train_no':self.tmp_list[2],
            'stationTrainCode':self.tmp_list[3],
            'seatType':seatType,
            'fromStationTelecode':from_station,
            'toStationTelecode':to_station,
            'leftTicket':self.tmp_list[12],
            'purpose_codes':'00',
            'train_location':self.tmp_list[15],
            '_json_att':'',
            'REPEAT_SUBMIT_TOKEN':rp,
        }
        data=urllib.urlencode(data)
        h=self.getPage('https://kyfw.12306.cn/otn/confirmPassenger/getQueueCount',data=data)
        print h
    def confirmOrder(self,s1,s2,rp,key_check_isChange):
            print '>>>准备提交订单!'
            data = {
                'passengerTicketStr':self.s1.encode('utf-8'),
                'oldPassengerStr':self.s2.encode('utf-8'),
                'randCode':'',
                'purpose_codes':'00',
                'key_check_isChange':key_check_isChange,
                'leftTicketStr':self.tmp_list[12],
                'train_location':self.tmp_list[15],
                'choose_seats':'',#1F
                'seatDetailType':'000',
                'roomType':'00',
                'dwAll':'N',
                '_json_att':'',
                'REPEAT_SUBMIT_TOKEN':rp
            }
            data=urllib.urlencode(data)
            h=self.getPage('https://kyfw.12306.cn/otn/confirmPassenger/confirmSingleForQueue',data=data)
            if h:
                #c.save(ignore_expires=True,ignore_discard=True)
                if json.loads(h)["data"]["submitStatus"]:
                    print('>>>车票自动提交成功\n',json.loads(h)["data"]["submitStatus"])
                    print('>>>正在获取订单结果!')
                    self.getResult(rp)
                    return True
                else:
                    print('>>>下单不成功,错误提示是:\n',json.loads(h)["data"]["errMsg"])
                    if json.loads(h)["data"]["errMsg"]=="验证码输入错误！":
                        self.code()
                    return False
            else:
                print('>>>自动提交请求返回的响应为空!')
    def checkUser(self):
        print '>>>执行checkUser检查用户状态是否有效!'
        h=self.getPage('https://kyfw.12306.cn/otn/login/checkUser',data='_json_att=')
        print h
        return h

    def submitOrderRequest(self,secretStr,train_date,tk,ar):
        print '>>>有票进入预定界面'
        import sys
        reload(sys)
        sys.setdefaultencoding('utf8')
        data='secretStr=%s&train_date=%s&back_train_date=%s&tour_flag=dc&purpose_codes=ADULT&query_from_station_name=%s&query_to_station_name=%s&undefined'%(secretStr,train_date,time.strftime('%Y-%m-%d'),tk,ar)
        h=self.getPage('https://kyfw.12306.cn/otn/leftTicket/submitOrderRequest',data=data)
        if 'globalRepeatSubmitToken = null' in h:
            print '>>>登陆已失效,重新登陆中'
            self.code()
            self.submitOrderRequest(secretStr,train_date,tk,ar)
            return h
        else:
            return h

    def getResult(self,rp):
        h=self.getPage('https://kyfw.12306.cn/otn/confirmPassenger/queryOrderWaitTime?random=%s&tourFlag=dc&_json_att=&REPEAT_SUBMIT_TOKEN=%s'%(int(time.time()),rp))
        h=json.loads(h)
        if h['data'].get('msg'):
            print(h['data']['msg'])
            if '对不起' in h['data']['msg']:
                print('>>>发送通知邮件!')
                dbs.exe("update train_order set state=8,remark='"+ h['data']['msg'] +"' where order_id="+order_id,1,1)
                sendmail(self.orderlist["email"],'%s-%s抢票结果'%(city2[self.tmp_list[6]],city2[self.tmp_list[7]]),'您订购的%s-%s不成功,失败原因是:%s!'%(city2[self.tmp_list[6]],city2[self.tmp_list[7]],h['data']['msg']))
                return False
            else:
                print('>>>发送通知邮件!')
                sendmail(self.orderlist["email"],'%s-%s抢票结果%s过期'%(city2[self.tmp_list[6]],city2[self.tmp_list[7]],(datetime.datetime.now()+datetime.timedelta(minutes=29)).strftime('%Y-%m-%d %H:%M:%S')),'您订购的%s-%s,时间%s-%s,历时%s车次为%s的车票已经于%s抢票成功,请在%s前登陆12306完成支付!'%(city2[self.tmp_list[6]],city2[self.tmp_list[7]],self.tmp_list[8],self.tmp_list[9],self.tmp_list[10],self.tmp_list[3],time.strftime('%Y-%m-%d %H:%M:%S'),(datetime.datetime.now()+datetime.timedelta(minutes=29)).strftime('%Y-%m-%d %H:%M:%S')))
                dbs.exe("update train_order set state=9,remark='订单完成' where order_id="+order_id,1,1)
                return True
        else:
            if self.count<3:
                print('>>>未获取到结果,3秒后再试!')
                self.count+=1
                time.sleep(2)
                self.getResult(rp)
            else:
                print('>>>获取结果超时!默认订单成功!请尽快登陆12306完成支付!')
                print('>>>发送通知邮件!')
                sendmail(self.orderlist["email"],'%s-%s抢票结果%s过期'%(city2[self.tmp_list[6]],city2[self.tmp_list[7]],(datetime.datetime.now()+datetime.timedelta(minutes=29)).strftime('%Y-%m-%d %H:%M:%S')),'您订购的%s-%s,时间%s-%s,历时%s车次为%s的车票已经于%s抢票成功,请在%s前登陆12306完成支付!'%(city2[self.tmp_list[6]],city2[self.tmp_list[7]],self.tmp_list[8],self.tmp_list[9],self.tmp_list[10],self.tmp_list[3],time.strftime('%Y-%m-%d %H:%M:%S'),(datetime.datetime.now()+datetime.timedelta(minutes=29)).strftime('%Y-%m-%d %H:%M:%S')))
                dbs.exe("update train_order set state=9,remark='订单完成' where order_id="+order_id,1,1)
                return True

    def order(self,secretStr):
        try:
            self.s1=self.orderlist.get('s1')
            self.s2=self.orderlist.get('s2')
            print self.s1,self.s2
            try:
                print '>>>正在尝试从cookie中获取登陆信息!'
                #self.c.load(ignore_expires=True,ignore_discard=True)
            except:
                pass
            if self.orderlist.get("passenger_name") and (not self.s1 or not self.s2):
                self.s1,self.s2=self.getPassInfo() #获取乘客信息
            h=self.checkUser()
            if h and json.loads(h)['data']['flag']:
                h=self.submitOrderRequest(secretStr,self.train_date,self.tk,self.ar)
                if "您还有未处理的订单" in h:
                    print "有未完成订单!请先处理!"
                    return True
                else:
                    print h
                rp,key_check_isChange=self.initDc()
                if not self.s1 or not self.s2:self.s1,self.s2=self.getPassenger(rp,key_check_isChange)
                self.checkOrderInfo(self.s1,self.s2,rp)
                self.getQueueCount(seatType,self.from_station,self.to_station,rp)
                if self.confirmOrder(self.s1,self.s2,rp,key_check_isChange):
                    return True

            else:
                print '>>>没有登陆,正在重新登陆!'
                if self.code():
                    if self.order(secretStr):
                        return True
                    else:
                        return False
                else:
                    self.code()
        except:
            raise
    def printTrain(self):
        global n
        print '[%s]%s %s [%s-%s] 历时:%s 二等:%s 一等:%s 硬座:%s 硬卧:%s 软卧:%s 无座:%s '%(n,self.tmp_list[13],self.tmp_list[3],self.tmp_list[8],self.tmp_list[9],self.tmp_list[10],self.tmp_list[30],self.tmp_list[31],self.tmp_list[29],self.tmp_list[28],self.tmp_list[23],self.tmp_list[26])
        secretStr=self.tmp_list[0]
        if secretStr:
            print '>>>查找到有票的车次,正在进入自动下单环节!'
            if self.order(secretStr):
                return True
    def findtrain(self,train_no=[]):
        try:
            html=self.getTrain(self.CLeftTicketUrl,self.train_date,city[self.orderlist.get("tk")],city[self.orderlist.get("ar")])
            print self.CLeftTicketUrl,self.train_date,city[self.orderlist.get("tk")],city[self.orderlist.get("ar")]
            while not html:
                time.sleep(3)
                html=self.getTrain(self.CLeftTicketUrl,self.train_date,city[self.orderlist.get("tk")],city[self.orderlist.get("ar")])
            global n
            global seatType
            n+=1
            print '>>>第%s次'%n,time.strftime('%H:%M:%S'),'查找车票中...'
            #print '>>>查找到以下车次信息:'
            for i in html:
                self.tmp_list=i.split('|')
                if train_no:#指定车次
                    if self.orderlist['choose_seats']=='二等座':
                        if self.tmp_list[3] in train_no:print '[%s]%s 二等座:%s'%(n,self.tmp_list[3],self.tmp_list[30])
                        if self.tmp_list[3] in train_no and self.tmp_list[30] !='无' and self.tmp_list[30] !='':
                            return self.printTrain()
                    elif self.orderlist['choose_seats']=='一等座':
                        if self.tmp_list[3] in train_no:print '[%s]%s 一等座:%s'%(n,self.tmp_list[3],self.tmp_list[31])
                        if self.tmp_list[3] in train_no and self.tmp_list[31] !='无' and self.tmp_list[31] !='':
                            return self.printTrain()
                    elif self.orderlist['choose_seats']=='硬卧':
                        if self.tmp_list[3] in train_no:print '[%s]%s 硬卧:%s'%(n,self.tmp_list[3],self.tmp_list[28])
                        if self.tmp_list[3] in train_no and self.tmp_list[28] !='无' and self.tmp_list[28] !='':
                            return self.printTrain()
                    elif self.orderlist['choose_seats']=='软卧':
                        if self.tmp_list[3] in train_no:print '[%s]%s 软卧:%s'%(n,self.tmp_list[3],self.tmp_list[23])
                        if self.tmp_list[3] in train_no and self.tmp_list[23] !='无' and self.tmp_list[23] !='':
                            return self.printTrain()
                    elif self.orderlist['choose_seats']=='硬座':
                        if self.tmp_list[3] in train_no:print '[%s]%s 硬座:%s'%(n,self.tmp_list[3],self.tmp_list[29])
                        if self.tmp_list[3] in train_no and self.tmp_list[29] !='无' and self.tmp_list[29] !='':
                            return self.printTrain()
                    else:
                        print '>>>选座条件:指定车次,座位不限!'
                        
                        if self.tmp_list[3] in train_no:
                            if self.tmp_list[30] !='无' and self.tmp_list[30] !='':
                                print '选了二等座'
                                seatType='O'
                                return self.printTrain()
                            elif self.tmp_list[31] !='无' and self.tmp_list[31] !='':
                                print '选了一等座'
                                seatType='M'
                                return self.printTrain()
                            elif self.tmp_list[28] !='无' and self.tmp_list[28] !='':
                                print '选了硬卧'
                                seatType='3'
                                return self.printTrain()
                            elif self.tmp_list[29] !='无' and self.tmp_list[29] !='':
                                print '选了硬座'
                                seatType='1'
                                return self.printTrain()
                            elif self.tmp_list[23] !='无' and self.tmp_list[23] !='':
                                seatType='4'
                                return self.printTrain()

                else:#不指定车次
                    if self.orderlist['choose_seats']=='二等座':
                        if self.tmp_list[30] !='无' and self.tmp_list[30] !='':
                            return self.printTrain()
                    elif self.orderlist['choose_seats']=='一等座':
                        if self.tmp_list[31] !='无' and self.tmp_list[31] !='':
                            return self.printTrain()
                    elif self.orderlist['choose_seats']=='硬卧':
                        if self.tmp_list[28] !='无' and self.tmp_list[28] !='':
                            return self.printTrain()
                    elif self.orderlist['choose_seats']=='软卧':
                        if self.tmp_list[23] !='无' and self.tmp_list[23] !='':
                            return self.printTrain()
                    elif self.orderlist['choose_seats']=='硬座':
                        if self.tmp_list[29] !='无' and self.tmp_list[29] !='':
                            return self.printTrain()
                    else:
                        print '>>>选座条件:有座位就行,座位不限'
                        if self.tmp_list[30] !='无' and self.tmp_list[30] !='':
                            print '选了二等座'
                            seatType='O'
                            return self.printTrain()
                        elif self.tmp_list[31] !='无' and self.tmp_list[31] !='':
                            print '选了一等座'
                            seatType='M'
                            return self.printTrain()
                        elif self.tmp_list[28] !='无' and self.tmp_list[28] !='':
                            print '选了硬卧'
                            seatType='3'
                            return self.printTrain()
                        elif self.tmp_list[29] !='无' and self.tmp_list[29] !='':
                            print '选了硬座'
                            seatType='1'
                            return self.printTrain()
                        elif self.tmp_list[23] !='无' and self.tmp_list[23] !='':
                            seatType='4'
                            return self.printTrain()
        except Exception as e:
            print e
            time.sleep(3)

    def searchTrain(self):
        print '>>>欢迎进入自动购票系统! [By侠仔]'
        self.orderlist["tk"]=raw_input(">>>请输入出发站名:").decode('utf-8')
        self.orderlist["ar"]=raw_input(">>>请输入到达站名:").decode('utf-8')
        self.train_date=raw_input(">>>请选择日期,默认是今天!(%s):"%time.strftime('%Y-%m-%d'))
        if not self.train_date:
            self.orderlist["train_date"]=time.strftime('%Y-%m-%d')
        else:
            self.orderlist["train_date"]=self.train_date
        html=self.getTrain(self.CLeftTicketUrl,self.orderlist["train_date"],city[self.orderlist.get("tk")],city[self.orderlist.get("ar")])
        while not html:
            time.sleep(3)
            html=self.getTrain(self.CLeftTicketUrl,self.orderlist["train_date"],city[self.orderlist.get("tk")],city[self.orderlist.get("ar")])
        n=0
        list2=[]
        for i in html:
            self.tmp_list=i.split('|')
            list2.append((n,self.tmp_list[13],self.tmp_list[3],city2[self.tmp_list[6]],city2[self.tmp_list[7]],self.tmp_list[8],self.tmp_list[9],self.tmp_list[10],self.tmp_list[30],self.tmp_list[31],self.tmp_list[29],self.tmp_list[28],self.tmp_list[23],self.tmp_list[26]))
            print '[%s]%s %s (%s-%s) [%s-%s] 历时:%s 二等:%s 一等:%s 硬座:%s 硬卧:%s 软卧:%s 无座:%s '%(n,self.tmp_list[13],self.tmp_list[3],city2[self.tmp_list[6]],city2[self.tmp_list[7]],self.tmp_list[8],self.tmp_list[9],self.tmp_list[10],self.tmp_list[30],self.tmp_list[31],self.tmp_list[29],self.tmp_list[28],self.tmp_list[23],self.tmp_list[26])
            n+=1
        No=raw_input(">>>请选择车次对应的序号,多个车次请使用,隔开:")
        if ',' in No:
            for x in No.split(','):
                self.orderlist["train_no"].append(list2[int(x)][2])
        else:
            self.orderlist["train_no"]=list2[int(No)][2]
        ss={'0':'二等座','1':'一等座','2':'硬卧','3':'硬座','4':'软卧'}
        self.orderlist["choose_seats"]=ss[raw_input("请选择坐席,不选默认任意座位(二等座0,一等座1,硬卧2,硬座3,软卧4):")]
        print('>>>您已选择了车次,请登录后选择乘车人!')
        global username,password
        username=raw_input(">>>请输入12306账号:")
        password=raw_input(">>>请输入12306密码:")
        #self.c.load(ignore_expires=True,ignore_discard=True)
        list2=self.getPassInfo()[2]
        No=raw_input(">>>请选择乘车人序号,多个乘车人,请使用,隔开:")
        if ',' in No:
            for x in No.split(','):
                self.orderlist["passenger_name"]+=list2[int(x)][1]+','
                self.orderlist["s1"]+='%s,0,1,%s,1,%s,%s,N_'%(seat.get(self.orderlist["choose_seats"]),list2[int(x)][1],list2[int(x)][2],list2[int(x)][3])
                self.orderlist["s2"]+='%s,1,%s,1_'%(list2[int(x)][1],list2[int(x)][2])
            self.orderlist["passenger_name"]=self.orderlist["passenger_name"][:-1]
        else:
            self.orderlist["passenger_name"]+=list2[int(No)][1]
            self.orderlist["s1"]+='%s,0,1,%s,1,%s,%s,N_'%(seat.get(self.orderlist["choose_seats"]),list2[int(No)][1],list2[int(No)][2],list2[int(No)][3])
            self.orderlist["s2"]+='%s,1,%s,1_'%(list2[int(No)][1],list2[int(No)][2])
        #print self.orderlist
if __name__=='__main__':
    n=0
    train=Train()
    dbs=db_pymsql.db_mysql()
    r=dbs.exe('select * from train_order where state=0',1,1)[0]
    print r
    train.username=r.get('username')
    train.password=r.get('password')
    train.orderlist['train_no']=r.get('train_no')
    train.orderlist['ar']=r.get('arrive_station')
    train.orderlist['passenger_name']=r.get('passenger')
    train.orderlist['tk']=r.get('start_station')
    order_id=r.get('order_id')
    #dbs.exe("update train_order set state=1,remark='开始调度' where state=0 and order_id="+order_id,1,1)
    if r:train.findtrain()
    #train.searchTrain()
    #train.code()
    #train.searchTrain()
    # if self.orderlist.get('choose_seats'):seatType=seat[self.orderlist.get('choose_seats')]
    # train_date=self.orderlist.get('train_date')
    # tk=self.orderlist.get('tk')#'南宁东'
    # ar=self.orderlist.get('ar')#'三水'
    # from_station=city[tk]
    # to_station=city[ar]
    # n=0
    #  #获取查票地址
    # while CLeftTicketUrl:
    #     if time.strftime('%H:%M:%S')>'07:00:00' and time.strftime('%H:%M:%S')<'23:00:00':
    #         if findtrain(self.orderlist["train_no"]):
    #             break
    #         else:
    #             time.sleep(2)


